package com.github.baichuan.application.scaffold.rest.controller;

import com.github.baichuan.application.scaffold.rest.domain.identity.ApplicationMemberService;
import com.github.baichuan.application.scaffold.rest.domain.identity.DingUser;
import com.github.baichuan.application.scaffold.rest.domain.identity.DingUserService;
import com.github.baichuan.application.scaffold.rest.domain.identity.Member;
import com.github.baichuan.mapping.BeanMapper;
import com.github.baichuan.web.dto.Result;
import com.github.baichuan.application.scaffold.rest.dto.dingtalk.User;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.Optional;

@Tag(name = "钉钉")
@RestController
@RequestMapping("/ding")
public class DingController {
    @Autowired
    private DingUserService dingUserService;
    @Autowired
    private ApplicationMemberService memberService;

    @Operation(summary = "钉钉用户绑定")
    @PostMapping("/user/bind/{memberUid}")
    public ResponseEntity<Result> bindUser(@RequestHeader("x-application-code") @Parameter(hidden = true) String application, @PathVariable String memberUid, @RequestBody User user){
        Result result = dingUserService.bind(application, memberUid, user);
        return ResponseEntity.ok(result);
    }

    @Operation(summary = "获取钉钉用户信息")
    @GetMapping("/user/{memberUid}")
    public ResponseEntity<Optional<User>> getUser(@RequestHeader("x-application-code") @Parameter(hidden = true) String application, @PathVariable String memberUid){
        Member member = memberService.find(application, memberUid).getMember();
        if(StringUtils.isNotBlank(member.getDingUnionId())){
            DingUser user = dingUserService.find(member.getDingUnionId());
            Optional<User> optionalUser = Optional.of(BeanMapper.map(user, User.class));
            return ResponseEntity.ok(optionalUser);
        } else {
            return ResponseEntity.ok(Optional.empty());
        }
    }
}
